<!-- 结合动态表单中的（下拉选项）使用
如果配置了（插槽名）为（SelectDict）
插槽配置{
  type: 'xxx', // 必填，字典名
  isDetail: false, // 不必填，如果填了为true，则显示当前选中的文本
}
-->
<template>
  <!-- 详情 -->
  <div v-if="props.isDetail" :class="attrs.class">{{ selectedLabel }}</div>

  <!-- 下拉框类型 -->
  <el-radio-group v-else-if="props.radio" v-model="value" :disabled="disabled" @change="handleChange">
    <el-radio v-for="(item, index) in _d.list" :key="index" :value="item.value">{{item.label}}</el-radio>
  </el-radio-group>
  <el-checkbox-group v-else-if="props.checkbox" v-model="value" :disabled="disabled" @change="handleChange">
    <el-checkbox v-for="(item, index) in _d.list" :key="index" :value="item.value">{{item.label}}</el-checkbox>
  </el-checkbox-group>
  <el-select v-else v-model="value" :disabled="disabled" style="width: 100%;" @change="handleChange">
    <template v-if="slots.tag" #tag>
      <slot name="tag"></slot>
    </template>
    <el-option
      v-for="(item, index) in _d.list"
      :key="index"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>
<script setup>
import { reactive, onMounted, ref, useAttrs, useSlots } from "vue";
import { listData } from "@/api/admin/dict.js";
import aDict from "./historyDict.js";

const attrs = useAttrs();
const slots = useSlots();
const emits = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
  modelValue: {
    type: [String, Number, null, Array],
    default: ''
  },
  value: {
    type: [String, Number, null, Array],
    default: ''
  },
  type: {
    type: String,
    default: ''
  },
  // 选项列表，在type为空时，使用这一个
  options: {
    type: Array,
    default: () => ([])
  },
  isDetail: {
    type: Boolean,
    default: false
  },
  designer: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否单选框
  radio: {
    type: Boolean,
    default: false
  },
  // 是否复选
  checkbox: {
    type: Boolean,
    default: false
  },
  // 是否下拉菜单 ---------
  dropdown: {
    type: Boolean,
    default: false
  },
})

const _d = reactive({
  list: [],
});

const value = computed({
  get() {
    let res = '';
    if(!isEmpty(props.modelValue)) {
      res = props.modelValue;
    } else if (!isEmpty(props.value)) {
      res = props.value;
    }

    // 如果是数组
    if(res instanceof Array) {
      res = res.map(item => String(item));
    } else {
      res = String(res);
    }
    return res;
  },
  set(val) {
    emits('update:modelValue', val);
  },
});

// 选中的项目
const selectedOption = computed(() => {
  return _d.list.find(item => item.value == value.value);
})

// 选中的值
const selectedLabel = computed(() => {
  return selectedOption.value?.label || '';
});

// 监听列表是否变化
watch(() => props.options, () => {
  if(!props.type) {
    _d.list = props.options;
  }
}, {
  immediate: true,
  deep: true
})


onMounted(() => {
  getData();
});

const getData = () => {
  if (!props.type) {
    return;
  }

  // 判断是否需要从历史获取
  let oDict = aDict.find(item => item.type == props.type);
  if(oDict) {
    _d.list = oDict.list;
    return;
  }

  let params = {
    pageNo: 1,
    pageSize: 999,
    type: props.type,
  };
  listData(params).then((res) => {
    _d.list = res.data.list.map(item => {
      let val = item.dictValue;
      item.label = item.dictLabel;
      item.value = val;
      return item;
    });
    // console.log(_d.list);
    // 添加到历史
    aDict.push({
      type: props.type,
      list: _d.list
    })
  });
};

// 获取label
const getLabel = () => {
  let oItem = _d.list.find((item) => item.value == value.value);
  return oItem ? oItem.label : "";
}

const handleChange = (valu) => {
  if (!valu) {
    emits("change", "");
  }
  if (props.multiple) {
    //多选
    let list = [];
    valu.map((item) => {
      _d.list.map((item2) => {
        if (item === item2?.value) {
          list.push(item2);
        }
      });
    });
    emits("change", list);
  } else {
    if (valu !== "") {
      const obj = _d.list.filter((item) => item?.value === valu)[0] || "";
      if (obj) {
        emits("change", obj);
      }
    }
  }
}

// 判断空
function isEmpty (val) {
  if (typeof val == 'string') {
    val = val.trim();
  }
  return !val && val!==0 && typeof val!=="boolean"?true:false;
}

defineExpose({
  getLabel,
  selectedOption,
  selectedLabel,
})

</script>
<style lang="scss" scoped>
</style>
